#!/bin/bash

# 配置变量
MYSQL_SERVER='node04'
OPENTSDB_SERVER='node02:14242'
HAZELCAST_NET='172.31.32.*'
HAZELCAST_GROUP='mango-lanniao'
ZOO_SERVER='node01 node02 node03'
KAFKA_SERVER='node01 node02 node03'
HAZELCAST_TYPE='tcp-ip'

# 解压jar包
uncompress_file(){
    mkdir ${package}_new
    cp $jar_file ${package}_new
    cd ${package}_new
    file_path=$(jar tvf $jar_file | egrep "$conf_file" | awk '{print $NF}')
    jar -xvf $jar_file $file_path
}

# 获取参数
get_var(){
    SERVICE=$1
    SERVICE_PORT=$2
    hostaddr=
    for node in $SERVICE; do
        hostaddr="$hostaddr $node:$SERVICE_PORT"
    done
}

# 将文件替换到压缩包内
replace_file(){
    jar -uvf $jar_file $file_path
    rm -rf $(echo $file_path | awk -F '/' '{print $NR}')
}

package=calc-task
jar_file="${package}-*.jar"
conf_file="application.properties|hazelcast-default.xml"

# 解压
uncompress_file

# 更换缓存分组
GET_HAZELCAST_GROUP="$(cat BOOT-INF/classes/hazelcast-default.xml | grep '<name>.*</name>' | awk -F '[>|<]' '{print $3}')"
sed -i "s#${GET_HAZELCAST_GROUP}#${HAZELCAST_GROUP}#" BOOT-INF/classes/hazelcast-default.xml
line=$(grep -rn 'interfaces enabled' BOOT-INF/classes/hazelcast-default.xml | awk -F ':' '{print $1}')
sed -i "$line s#false#true#" BOOT-INF/classes/hazelcast-default.xml
sed -i "s#10.10.1.*#${SUB_NET}</interface>#" BOOT-INF/classes/hazelcast-default.xml

# 选择组网方式
if [ "$HAZELCAST_TYPE" == 'tcp-ip' ]; then
    echo '组网方式配置为 tcp-ip'
    /usr/bin/cp ../hazelcast.xml.tcp-ip BOOT-INF/classes/hazelcast-default.xml
fi

# 打包
replace_file

# 重命名源文件
mv $(ls ../${package}*.jar) $(ls ../${package}*.jar).source.$(date +%s)
cp $(ls ./${package}*.jar) ../

# 清理临时文件
cd ../
rm  -rf ./${package}_new

# 获取 mysql 默认配置
GET_MYSQL_SERVER=$(cat application.properties.default | grep jdbc:mysql | awk -F '[//|/]' '{print $3}')

# 拼接 kafka 参数
get_var "$KAFKA_SERVER" "9092"
KAFKA_LIST=$(echo $hostaddr |sed 's# #,#g')

# 拼接zookeeper 参数
get_var "$ZOO_SERVER" "2181"
ZOOK_LIST=$(echo $hostaddr |sed 's# #,#g')

# 获取 opentsdb 配置
GET_OPENTSDB_SERVER=$(cat application.properties.default | grep otsdb.url | awk -F '//' '{print $2}')

sed \
  -e "s#${GET_MYSQL_SERVER}#${MYSQL_SERVER}:3306#" \
  -e "s#kafka.url=.*#kafka.url=$KAFKA_LIST#" \
  -e "s#zookeeper.url=.*#zookeeper.url=$ZOOK_LIST#" \
  -e "s#hbase.zk.quorum=.*#hbase.zk.quorum=$ZOOK_LIST#" \
  -e "s#${GET_OPENTSDB_SERVER}#${OPENTSDB_SERVER}#" \
    application.properties.default > application.properties